﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;

using RexToy.Logging;

namespace Monitor.Core
{
    public class Scheduler
    {
        private static object locker = new object();
        private Thread executor;
        private DataWriter writer = new DataWriter();
        private static ILog _log = LogContext.GetLogger<Scheduler>();

        private void Execute()
        {
            while (true)
            {
                lock (locker)
                {
                    foreach (ISensor s in _list)
                    {
                        if (DateTime.Now - s.LastRefreshTime > new TimeSpan(0, 0, 0, 0, s.Interval))
                        {
                            try
                            {
                                ServiceStatus status = s.Ping();
                                _log.Info(s.Description + ": " + status);
                                if (status != ServiceStatus.Alive)
                                {
                                    _log.Info(s.LastError);
                                }                                
                            }
                            catch (Exception ex)
                            {
                                _log.Error("Unhandled Exception: " + ex.Message);
                            }
                            writer.Write(s);
                        }

                    }
                }
                Thread.Sleep(5000);
            }
        }

        private List<ISensor> _list = new List<ISensor>();
        public void Start()
        {
            executor = new Thread(new ThreadStart(this.Execute));
            executor.Start();
        }

        public void Stop()
        {
            executor.Abort();
        }

        public void PushSensor(ISensor s)
        {
            lock (locker)
            {
                _list.Add(s);
            }
        }

        public void PopSensor(ISensor s)
        {
            lock (locker)
            {
                _list.Remove(s);
            }
        }
    }
}
